# -*- coding: utf-8 -*-
# This code is opensource under WTFPL.
# Author: squaresum
import json
import downloader
from lxml import etree


def IIIFParser(jsonStr):
    """
    解析IIIF Manifest JSON的内容，提取图片链接，形成列表并返回。
    """
    data = json.loads(jsonStr)
    picList = []
    for item in data['sequences'][0]['canvases']:
        picList.append(item['images'][0]['resource']['@id'])
    return picList


def TokyoViewParser(htmlStr, url, isOriginal):
    """
    解析东京大学史料编纂所ships viewer列表页面，根据规律返回图片链接列表。
    """
    page = etree.HTML(htmlStr)
    numElements = page.xpath(
        '//*[@id="sidemenu"]/div[1]/div[2]/div[1]/span[2]')
    num = int(numElements[0].text)
    if isOriginal:
        link = 'https://clioimg.hi.u-tokyo.ac.jp/viewer/image/idata/' + \
            '/'.join(url.split('/')[-4:-1])
        return ['{}/{}.jpg'.format(link, numberFormater(i, 8)) for i in range(1, num+1)]
    else:
        link = 'https://clioimg.hi.u-tokyo.ac.jp/viewer/image/idata/' + \
            '/'.join(url.split('/')[-5:-1])
        return ['{}/{}.tif'.format(link, numberFormater(i, 4)) for i in range(1, num+1)]


def TokyoListParser(htmlStr, isOriginal):
    """
    解析东京大学史料编纂所ships viewer图片查看页面，根据规律返回图片链接列表。
    """
    page = etree.HTML(htmlStr)
    linkElements = page.xpath('//*[@id="image-list"]/div[1]/a[2]')
    link = linkElements[0].get('href')
    viewPageHtmlStr = downloader.getContent(link)
    picList = TokyoViewParser(viewPageHtmlStr, link, isOriginal)
    return picList

def HathiTrustListParser(htmlStr, id):
    page = etree.HTML(htmlStr)
    pagenumElements = page.xpath('//input[@id="range-seq"]')
    pagenum = int(pagenumElements[0].get('max'))
    picList = ['https://babel.hathitrust.org/cgi/imgsrv/image?id={};seq={};size=100;rotation=0'.format(id, num) for num in range(1, pagenum+1)]
    return picList



def numberFormater(num, length):
    """
    按照指定的位数自动在数字前面补零的工具函数。
    """
    if len(str(num)) >= length:
        return str(num)

    return ''.join(['0' for i in range(length - len(str(num)))] + list(str(num)))
